package demo1;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:实现一个最小栈
 * User: WHY
 * Date: 2022-07-10
 * Time: 21:54
 */
public class MinStack {
    private Stack<Integer>  p;
    private Stack<Integer>minStack;



    public MinStack() {
        p=new Stack<>();
        minStack=new Stack<>();
    }
/*
* 入栈
* */
    public void push(int val) {
        p.push(val);
        if(minStack.empty()){
            minStack.push(val);
        }else{
            int peekV=minStack.peek();//看一眼
            if(val<=peekV){
                minStack.push(val);
            }

        }

    }

    public void pop() {
        if(!p.empty()){
           int popV=p.pop();
           int peekVMinS=minStack.peek();
           if(popV==peekVMinS){
               minStack.pop();
           }
        }

    }
//获取栈顶元素，但是不删除
    public int top() {
        if(!p.empty()){
            return p.peek();
        }
        return -1;
    }

    public int getMin() {
        if(!minStack.empty()){
            return minStack.peek();
        }
return -1;
    }
}
